#!/usr/bin/env python
"""
使用示例脚本
演示如何使用ScalpingBot的各个模块
"""
import sys
import os
from datetime import datetime, timedelta

# 添加项目路径
sys.path.insert(0, os.path.dirname(os.path.abspath(__file__)))

from src.utils.config import Config
from src.utils.logger import get_logger
from src.okx.client import OKXClient
from src.data.kline import KlineDataFetcher
from src.data.processor import KlineProcessor
from src.strategy.scalping import ScalpingStrategy
from src.trading.executor import TradeExecutor
from src.backtesting.engine import BacktestEngine
from src.simulator.mock_exchange import MockExchange
from src.costs.calculator import CostCalculator

logger = get_logger(__name__)


def example_1_basic_api_usage():
    """示例1: 基础API使用"""
    print("\n" + "="*60)
    print("示例1: 基础API使用")
    print("="*60)

    # 加载配置
    config = Config.load()

    # 初始化客户端
    client = OKXClient(
        api_key=config.get('api.api_key', 'test_key'),
        secret_key=config.get('api.secret_key', 'test_secret'),
        passphrase=config.get('api.passphrase', 'test_phrase'),
        environment='sandbox',
        simulate=True
    )

    # 获取K线数据
    symbol = 'BTC-USDT'
    klines = client.get_klines(symbol, 5, limit=50)
    print(f"获取 {len(klines)} 条K线数据")

    if klines:
        latest = klines[-1]
        print(f"最新K线: 开={latest.open}, 高={latest.high}, 低={latest.low}, 收={latest.close}")

    # 获取行情
    ticker = client.get_ticker(symbol)
    if ticker:
        print(f"最新行情: 价格={ticker['last_price']}, 变化={ticker['change_24h']}%")


def example_2_data_processing():
    """示例2: 数据处理和技术指标"""
    print("\n" + "="*60)
    print("示例2: 数据处理和技术指标计算")
    print("="*60)

    config = Config.load()
    client = OKXClient(
        api_key=config.get('api.api_key', 'test_key'),
        secret_key=config.get('api.secret_key', 'test_secret'),
        passphrase=config.get('api.passphrase', 'test_phrase'),
        environment='sandbox',
        simulate=True
    )

    # 获取K线
    symbol = 'BTC-USDT'
    klines = client.get_klines(symbol, 5, limit=100)

    if not klines:
        print("无法获取K线数据")
        return

    # 处理K线
    processor = KlineProcessor()
    df = processor.add_klines(symbol, 5, klines)

    # 添加技术指标
    df = processor.add_technical_indicators(df, config.get('strategy', {}))

    print(f"K线数据: {len(df)} 条")
    print(f"\n最新K线数据:")
    print(df[['close', 'rsi', 'macd', 'macd_signal', 'bb_upper', 'bb_lower']].tail())


def example_3_strategy_signal():
    """示例3: 策略信号生成"""
    print("\n" + "="*60)
    print("示例3: 策略信号生成")
    print("="*60)

    config = Config.load()
    client = OKXClient(
        api_key=config.get('api.api_key', 'test_key'),
        secret_key=config.get('api.secret_key', 'test_secret'),
        passphrase=config.get('api.passphrase', 'test_phrase'),
        environment='sandbox',
        simulate=True
    )

    # 获取多时间框架数据
    symbol = 'BTC-USDT'
    processor = KlineProcessor()
    strategy = ScalpingStrategy(config.get('strategy', {}))

    kline_data = {}
    for timeframe in [5, 15, 60, 240]:
        klines = client.get_klines(symbol, timeframe, limit=100)
        if klines:
            df = processor.add_klines(symbol, timeframe, klines)
            df = processor.add_technical_indicators(df, config.get('strategy', {}))
            kline_data[timeframe] = df

    # 生成信号
    signal, confidence = strategy.generate_signal(kline_data)
    print(f"信号: {signal}, 信心度: {confidence:.2f}")


def example_4_cost_calculation():
    """示例4: 成本计算"""
    print("\n" + "="*60)
    print("示例4: 成本计算")
    print("="*60)

    calc = CostCalculator(maker_fee=0.02, taker_fee=0.05, funding_rate=0.03)

    # 模拟交易
    entry_price = 40000.0
    exit_price = 40800.0
    quantity = 1.0

    # 计算盈亏
    result = calc.calculate_profit_loss(
        entry_price=entry_price,
        exit_price=exit_price,
        quantity=quantity,
        trade_type='spot'
    )

    print(f"入场价格: ${entry_price}")
    print(f"出场价格: ${exit_price}")
    print(f"交易数量: {quantity}")
    print(f"\n盈亏分析:")
    print(f"  毛盈亏: ${result['gross_pnl']:.2f} ({result['gross_pnl_pct']:.2f}%)")
    print(f"  入场手续费: ${result['entry_fee']:.2f}")
    print(f"  出场手续费: ${result['exit_fee']:.2f}")
    print(f"  总手续费: ${result['trading_fee']:.2f}")
    print(f"  净盈亏: ${result['net_pnl']:.2f} ({result['net_pnl_pct']:.2f}%)")

    # 计算盈亏平衡点
    breakeven = calc.calculate_breakeven_price(entry_price, quantity, quantity)
    print(f"\n盈亏平衡点: ${breakeven:.2f}")


def example_5_mock_exchange():
    """示例5: 模拟交易所"""
    print("\n" + "="*60)
    print("示例5: 模拟交易所")
    print("="*60)

    # 初始化模拟交易所
    initial_balances = {
        'USDT': 5000.0,
        'BTC': 0.0,
        'ETH': 0.0,
    }
    exchange = MockExchange(initial_balances)

    # 设置价格
    exchange.set_ticker('BTC-USDT', 40000.0)
    exchange.set_ticker('ETH-USDT', 2000.0)

    # 执行交易
    print("\n执行模拟交易:")

    # 买入BTC
    result = exchange.place_order('BTC-USDT', 'buy', 'market', 0.1)
    print(f"买入0.1 BTC: {result.success}")

    # 查看余额
    balances = exchange.get_balance()
    for balance in balances:
        print(f"  {balance.currency}: {balance.balance:.2f}")

    # 卖出部分BTC
    result = exchange.place_order('BTC-USDT', 'sell', 'market', 0.05)
    print(f"\n卖出0.05 BTC: {result.success}")

    # 最终余额
    balances = exchange.get_balance()
    print("\n最终余额:")
    for balance in balances:
        print(f"  {balance.currency}: {balance.balance:.2f}")


def example_6_simple_backtest():
    """示例6: 简单回测"""
    print("\n" + "="*60)
    print("示例6: 简单回测")
    print("="*60)

    config = Config.load()

    # 修改配置为回测模式
    config._config['backtest']['start_date'] = '2024-06-01'
    config._config['backtest']['end_date'] = '2024-06-07'
    config._config['backtest']['initial_balance'] = 10000

    # 初始化回测引擎
    engine = BacktestEngine(config._config, initial_balance=10000)

    print("回测配置:")
    print(f"  初始资金: ${engine.initial_balance}")
    print(f"  开始日期: 2024-06-01")
    print(f"  结束日期: 2024-06-07")
    print(f"  交易对: BTC-USDT")

    print("\n注意: 实际回测需要从OKX获取历史K线数据")
    print("详见 main.py 的 run_backtest() 方法")


def main():
    """运行所有示例"""
    print("\n" + "="*60)
    print("ScalpingBot 使用示例")
    print("="*60)

    try:
        # 示例1: 基础API
        # example_1_basic_api_usage()

        # 示例2: 数据处理
        # example_2_data_processing()

        # 示例3: 策略信号
        # example_3_strategy_signal()

        # 示例4: 成本计算
        example_4_cost_calculation()

        # 示例5: 模拟交易所
        example_5_mock_exchange()

        # 示例6: 回测
        example_6_simple_backtest()

        print("\n" + "="*60)
        print("所有示例运行完成")
        print("="*60)

    except Exception as e:
        logger.error(f"示例运行出错: {str(e)}")
        import traceback
        traceback.print_exc()


if __name__ == '__main__':
    main()
